#!/bin/bash
# 检查apm进程的物理内存占用量,超过阈值时重启apm

MAX_MEM=2 # Gbytes
LOG_DIR=/opt/apm/analyze/dist/logs/
LOG_FILE=${LOG_DIR}crit.log
CHECK_INTERVAL=5 # seconds

[[ ! -d ${LOG_DIR} ]] && mkdir -p ${LOG_DIR}

while :
do
    PID_OF_APM=`pidof apm`
    mem=`pmap -x ${PID_OF_APM} 2>/dev/null | awk '/total/ { print $4 / 1024 / 1024 }'`
    time=`date +"%F %T"`
    if [[ -z ${mem} ]]; then
        echo "apm is not running"
    elif [[ `echo "$mem ${MAX_MEM}" | awk '{if($1>$2){print 1}else{print 0}}'` -eq 1 ]];then
        echo "$time memory of apm(pid ${PID_OF_APM}) ${mem}G is great than ${MAX_MEM}G, kill apm now..." | tee -a ${LOG_FILE}
        kill -9 ${PID_OF_APM} && /opt/apm/analyze/dist/script/run_apm.sh
    else
        echo "$time memory of apm(pid ${PID_OF_APM}) ${mem}G is ok..."
    fi
    sleep ${CHECK_INTERVAL}
done
